package mark.tom.gear.base.utils

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.Dimension
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.snackbar.Snackbar.SnackbarLayout

object SnackBarUtil {

    fun showSnackBar(mContext: Context, @StringRes messageId: Int) {
        showSnackBar(mContext, mContext.getString(messageId))
    }

    fun showSnackBar(mContext: Context, message: CharSequence) {
        if (mContext !is Activity || mContext.isFinishing) {
            return
        }
        val contentView = (mContext.findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(0)
        setTextColorAndSize(shortMake(contentView, message), 0, 0f, 10).show()
    }

    private fun shortMake(view: View, message: CharSequence): Snackbar {
        return Snackbar.make(view, message, Snackbar.LENGTH_SHORT)
    }

    private fun shortMake(view: View, messageId: Int): Snackbar {
        return Snackbar.make(view, messageId, Snackbar.LENGTH_SHORT)
    }

    private fun longMake(view: View, message: CharSequence): Snackbar {
        return Snackbar.make(view, message, Snackbar.LENGTH_LONG)
    }

    private fun longMake(view: View, messageId: Int): Snackbar {
        return Snackbar.make(view, messageId, Snackbar.LENGTH_LONG)
    }

    fun setSnackBarAlpha(snackBar: Snackbar, alpha: Float): Snackbar {
        val snackBarView = getSnackBarLayout(snackBar)
        snackBarView.alpha = alpha
        return snackBar
    }

    fun setSnackBarBackgroundColor(snackBar: Snackbar, @ColorInt color: Int): Snackbar {
        val snackBarView = getSnackBarLayout(snackBar)
        snackBarView.setBackgroundColor(color)
        return snackBar
    }

    fun setSnackBarBackgroundResource(snackBar: Snackbar, @DrawableRes resId: Int): Snackbar {
        val snackBarView = getSnackBarLayout(snackBar)
        snackBarView.setBackgroundResource(resId)
        return snackBar
    }

    private fun setTextColorAndSize(snackBar: Snackbar, @ColorInt color: Int, @Dimension size: Float, maxLines: Int): Snackbar {
        val snackBarView = getSnackBarLayout(snackBar)
        val snackBarTextView = snackBarView.findViewById<View>(com.google.android.material.R.id.snackbar_text) as TextView
        if (color != 0) {
            snackBarTextView.setTextColor(color)
        }
        if (size != 0f) {
            snackBarTextView.textSize = size
        }
        if (maxLines > 0) {
            snackBarTextView.maxLines = maxLines
        }
        return snackBar
    }

    private fun getSnackBarLayout(snackBar: Snackbar): SnackbarLayout {
        return snackBar.view as SnackbarLayout
    }
}